package com.share.auth.service;

import com.share.common.core.domain.Result;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.ip.IpUtils;
import com.share.system.api.model.LoginUser;
import com.share.user.api.RemoteH5UserService;
import com.share.user.domain.UpdateUserLogin;
import com.share.user.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class UniappService {

    @Autowired
    private RemoteH5UserService remoteH5UserService;

    //微信用户登录
    public LoginUser wxLogin(String code) {
        //1 判断code是否为空
        if (code == null){
            throw new ServiceException("微信code必须填写");
        }

        //2 通过code远程调用user模块进行登录
        Result<UserInfo> userInfoResult = remoteH5UserService.wxLogin(code);
        UserInfo userInfo = userInfoResult.getData();

        //3 获取到userInfo后 判断userInfo是否为空
        if (userInfoResult.getData() == null){
            throw new ServiceException("微信授权登录失败");
        }

        //用户状态为2为被禁用
        if (userInfo.getStatus().equals("2")){
            throw new ServiceException("对不起，您的账号：" + userInfo.getWxOpenId() + " 已停用");
        }

        //4 封装数据返回
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(userInfo.getWxOpenId());
        loginUser.setStatus(userInfo.getStatus()+"");

        //更新用户登录信息
        UpdateUserLogin updateUserLogin = new UpdateUserLogin();
        updateUserLogin.setUserId(userInfo.getId());  //id
        updateUserLogin.setLastLoginIp(IpUtils.getIpAddr()); //登录ip
        updateUserLogin.setLastLoginTime(new Date()); //最后登录时间
        remoteH5UserService.updateUserLogin(updateUserLogin);

        return loginUser;
    }
}
